//
//  SEChatModel.swift
//  SmartEyeForPatient
//
//  Created by QDSG on 2021/4/26.
//

import HandyJSON

/// 处方状态：0未审核，1审核通过2驳回,3付款成功,4医生撤销,5未开药
enum SEChatPrescriptionStatus: Int, HandyJSONEnum, Codable {
    case unreviewed, passed, rejected, paid, revoked, noDrug
    
    var text: String? {
        switch self {
        case .unreviewed:   return "审核中"
        case .passed:       return "待支付"
        case .rejected:     return "被驳回"
        case .paid:         return "已支付"
        case .revoked:      return "医生已撤销"
        case .noDrug:       return "未开药"
        }
    }
    
    var textColor: UIColor {
        switch self {
        case .unreviewed:   return Asset.main.color
        case .passed,
             .paid,
             .noDrug:       return Asset.textDark.color
        case .rejected:     return Asset.warn.color
        case .revoked:      return Asset.textGray.color
        }
    }
    
    var descColor: UIColor { return Asset.textGrayLightest.color }
    
    var deleteHidden: Bool {
        switch self {
        case .unreviewed,
             .rejected: return false
        default:        return true
        }
    }
    
    var payButtonHidden: Bool {
//        switch self {
//        case .passed: return false
//        default:      return true
//        }
        return true
    }
}

/// 消息 cmd
enum SEChatCMD: Int {
    case message     = 11   // 聊天消息
    case receive     = 108  // 接收方收到消息后回复
    case sendSuccess = 109  // 服务端主动通知发送端，收到109发送代表发送消息成功
    case haveRead    = 110  // 接收方在聊天页面时回复，服务端更新最新已读消息id
    case heartbeat   = 113  // 客户端定时发送，服务端监测，5秒钟发送一次
    
    case inquiryStatusChanged = 507         // 问诊状态发生变化
    
    case prescriptionStatusChanged = 508    // 处方状态发生变化
    
    case guideInquiryEnd = 802              // 导诊自动结束
    
    case logout = 401                       // Token过期
    
    case unknown     = -1
}

/// 发送者类型
/// 0 - 基层（患者）, 1 - 专家, 2 - 处方审核通过推送给开方医生, 3 - 导诊客服
enum SEChatSenderType: Int {
    case patient, expert, review, customer
}

/// 聊天消息内容类型
/// 0 - 文字, 1 - 图片, 2 - 语音, 3 - 视频, 4 - 处方, 5 - 诊断, 6 - 眼科检查AI报告, 7 - 患者档案调阅, 8 - 结束问诊确认, 9 - 视频通话消息
enum SEChatMessageType: Int, HandyJSONEnum, Codable {
    case text, image, voice, video, prescription, diagnosis, checkReport, fileAuthorize, endInquiry, videoCall, start = 100, end, time
    
    var title: String {
        switch self {
        case .start: return "问诊已开始"
        case .end:   return "问诊已结束"
        default:     return ""
        }
    }
}

/// 聊天类型
/// 0 - 未知, 1 - 线上问诊, 2 - 会诊, 3 - 导诊
enum SEChatType: Int {
    case unknown, onlineInquiry, consultation, gudieInquiry
    
    var ackType: SEChatMessageFromType {
        switch self {
        case .onlineInquiry, .gudieInquiry:
            return .private
        default:
            return .group
        }
    }
}

/// 聊天消息类型
/// 1 - 私聊, 2 - 群聊, 3 - 推送
enum SEChatMessageFromType: Int {
    case `private` = 1, group, push
}

/// 聊天消息发送状态
/// 成功, 失败, 正在发送
enum SEChatMessageSendStatus: Int, Codable {
    case success, failure, sending
}

// MARK: - CHAT MODEL

struct SEChatModel: HandyJSON {
    var pageNum: Int = 0
    var pageSize: Int = 0
    var total: Int = 0
    var totalPage: Int = 0
    var list: [SEChatRecord]?
}

struct SEChatRecord: HandyJSON, Codable {
    var fromUserId: String?     // 发送者userId
    var toUserId: String?       // 接收者userId
    var relationId: String?     // 关联业务id，如诊断id
    var createTime: String?     // 消息创建时间
    var msgId: String?          // 消息id
    var relativeType: Int = 0   // 发送者类型 0 基层(患者) 1 专家 2处方审核通过推送给开方医生 3 导诊客服
    var msgType: Int = 0        // 消息类型 0:文字、1:图片、2:语音、3:视频、4:处方、5:诊断
    var chatType: Int = 0       // 聊天类型(0:未知,1:图文咨询,2:会诊,3:导诊)
    var groupId: String?        // 群组id仅在chatType为2时需要
    var content: String?        // 消息内容(如果是图片存缩略图url,是处方、诊断存对应id)
    var url: String?            // 图片高清url
    var extras: String?         // 扩展字段,JSON字符串格式如：{'扩展字段名称':'扩展字段value'}
    var ackType: Int = 0        // 1:私聊  2:群聊  3:推送
    var cmd: Int = 0            // 消息 cmd
    
    var hbbyte: String?
    
    var messageSendStatus: SEChatMessageSendStatus = .success // 发送消息的状态
    var code: Int = 0
    
    var status: SEInquiryChangeStatus = .waitPay
    
    var prescription: Prescription?
    
    struct Prescription: HandyJSON, Codable {
        var id: String?
        var bisType: Int = 0
        var bisId: String?
        var totalExpense: Double = 0.0
        var status: SEChatPrescriptionStatus = .unreviewed
        var proposal: String?
        var drugName: String?
        var diagnoseName: String?
    }
}

extension SEChatRecord {
    /// 后一条数据和前一条数据是否间隔 2 分钟以上
    func isLateForTwoMinutes(_ targetModel: SEChatRecord) -> Bool {
        guard let previousTime = targetModel.createTime else { return true }
        
        let previousDate = Date.stringToDate(previousTime)
        let nextDate = Date.stringToDate(createTime ?? "")
        
        let previousSeconds = previousDate.milliseconds / 1000
        let nextSeconds = nextDate.milliseconds / 1000
        
        SELog("previousSeconds = \(previousSeconds)")
        SELog("nextSeconds = \(nextSeconds)")
        
        return (nextSeconds - previousSeconds) > 120
    }
    
    var timeDate: Date? {
        guard let createTime = createTime else { return nil }
        let seconds = Date.stringToDate(createTime).milliseconds / 1000
        return Date(timeIntervalSince1970: seconds)
    }
}

struct SEChatRecordExtras: HandyJSON {
    var id: String?
    var status: SEInquiryChangeStatus = .waitPay
    var prescriptionDto: SEChatRecord.Prescription?
}

struct SEChatCheckReport: HandyJSON {
    var id: String?
    var name: String?
    var time: String?
    var list: [String]?
    var checkHosId: String?
    var reportTitle: String?
    var status: Int?
}
